GHOST = {}

GHOST.Entity = nil
GHOST.NextSpawn = 0.0

function GHOST:CreateGhost()

	if !IsValid( self.Entity ) then
		self.Entity = ents.Create("prop_physics")
		self.Entity:Spawn()
	end	
	
	self:UpdateModel()

end

function GHOST:ResetTimer()
	GHOST.NextSpawn = CurTime() + 0.5
end

function GHOST:UpdateModel()

	local model = BUILDING:GetModel()
	
	if IsValid( self.Entity ) && model then
		self.Entity:SetModel( model )
	end

end

function GHOST:DestroyGhost()
	if IsValid( self.Entity ) then
		self.Entity:Remove()
	end
end

function GHOST:DEBUG()
	local mins = GHOST.Entity:OBBMins() * 0.99
	local maxs = GHOST.Entity:OBBMaxs() * 0.99
	
	mins:Rotate( GHOST.Entity:GetAngles() )
	maxs:Rotate( GHOST.Entity:GetAngles() )
	
	mins = mins + GHOST.Entity:GetPos() + self.Entity:GetUp()
	maxs = maxs + GHOST.Entity:GetPos() + self.Entity:GetUp()
	
	DEBUG:Box( mins, maxs )
end


function GHOST:ShowCollisionPoint()
	local trace = BUILDING:GetTrace( self.Entity )
	
	PrintTable( trace )
	
	DEBUG:Box( trace.HitPos + Vector(2,2,2) , trace.HitPos - Vector(2,2,2) )
end

function GHOST:Think()

	if !IsValid( self.Entity ) then	
		self:CreateGhost()
		return
	end
	
	local Trace = BUILDING:PlayerTrace( LocalPlayer() )	
	
	BUILDING:UpdatePos( Trace, self.Entity )
	
	if Trace.Hit && BUILDING:CanSpawn( self.Entity ) then
		self.Entity:SetColor( 80,255,80, 255 )
	else
		self.Entity:SetColor( 255,80,80, 255 )
	end

end


hook.Add("BuildChoose", "GarcBuilder", function()
	GHOST:UpdateModel()
end )

hook.Add("PlayerDeath", "RemoveGhost", function( ply )

	if ply == LocalPlayer() then
		GHOST:DestroyGhost()
	end

end) 
